import time

from selenium import webdriver
from selenium.webdriver.common.by import By

# 实例化Options来创建启动参数对象
options = webdriver.ChromeOptions()
# 启动无痕模式运行
options.add_argument('--incognito')
# 设置窗口最大化运行
options.add_argument('--start-maximized')
# 取消Chrome正受到自动测试软件的控制的提示
options.add_experimental_option('useAutomationExtension', False)
options.add_experimental_option("excludeSwitches", ['enable-automation'])
# 启动浏览器
driver = webdriver.Chrome(options=options)
# 设置隐式等待
driver.implicitly_wait(3)
# 防止被反爬
driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
    "source": """
    Object.defineProperty(navigator, 'webdriver', {
      get: () => false
    })
  """
})

# 访问百度首页
driver.get('https://www.baidu.com/')
time.sleep(3)

# 获取当前窗口句柄
current_window_handle = driver.current_window_handle
print("current_window_handle:", current_window_handle)

# 点击左上角的新闻
driver.find_element(By.CSS_SELECTOR, 'div#s-top-left > a').click()
time.sleep(3)

# 获取当前已打开的所有窗口句柄
window_handles = driver.window_handles
print("window_handles:", window_handles)

# 切换到百度新闻window
driver.switch_to.window(window_handles[-1])

# 获取热搜新闻词
hot_words = driver.find_element(By.CSS_SELECTOR, 'ul.hotwords').text
print("hot_words:", hot_words)

time.sleep(3)

# 退出浏览器
driver.quit()
